module repository.GroupApplyRepository;

import bootstrap.DatabaseBootstrap;
import hunt.entity;
import hunt.logging;
import std.conv : to;
import model;
import message.MsgDefine;
import core.stdc.time;

import hunt.framework;

class GroupApplyRepository : EntityRepository!( GroupApply , int){

  this()
  {
    super(defaultEntityManager());
  }

  GroupApply[] getUntreated(string toId)
  {
    scope(exit)
    {
      _manager.close();
    }
    auto query = _manager.createQuery!(GroupApply)("select * from GroupApply a where a.toId = :toId AND a.status = 0").
    setParameter("toId", toId);
    GroupApply[] objs = query.getResultList();
    logInfo ("getUntreated size: %d",objs.length);
    return objs;
  }

  void addGroupApply(ApplyGroup req , uint type)
  {
    scope(exit)
    {
      _manager.close();
    }
    auto insert = _manager.createQuery!(GroupApply)("INSERT INTO GroupApply u(u.groupId,u.fromId,u.toId,u.applyTime,u.aliasName,u.newMember,u.status) VALUES (:groupId,:fromId,:destination,:time,:username,:newMember,:type)");
    insert.setParameter("groupId",to!uint(req.groupId));
    insert.setParameter("fromId",to!uint(req.fromId));
    insert.setParameter("destination",to!uint(req.destination));
    insert.setParameter("time",core.stdc.time.time(null));
    insert.setParameter("username",req.username);
    insert.setParameter("newMember",to!uint(req.newMember));
    insert.setParameter("type",type);
    insert.exec();
  }

  void updateGroupApply(string groupId, string fromId, string toId, bool succeeded)
  {
    scope(exit)
    {
      _manager.close();
    }
    auto update = _manager.createQuery!(GroupApply)("UPDATE GroupApply u SET u.status = :status where  " ~
    "u.groupId = :groupId and u.fromId = :fromId and u.toId = :toId" );
    update.setParameter("status",succeeded? 1:2);
    update.setParameter("groupId",groupId);
    update.setParameter("fromId",fromId);
    update.setParameter("toId",toId);
    try{
      update.exec();
    }
    catch(Exception e)
    {
      logError("updateStatus error : %s",e.msg);
    }
  }

}

